<template>
<view>
<!-- <navigator  url='../orderdetail/orderdetail'> -->
<view class="tabs">
	<text v-for="(item, index) in tabs" :key="index" :class="index === tab ? 'active' : ''" @tap="select" :data-index="index">{{item}}</text>
</view>
<!-- 收货地址 -->
<view class="changeAddress" @tap="toChangeAddress" v-if="!showMove">
	<image src="/static/remao_shop/img/address.png"></image>
	<view class="addressList" :hidden="isShowAddress">
		<view class="addressList-list">
			<view class="addressList-list-top">
				<image src="/static/remao_shop/img/dingwei.png"></image>
				<view>
					<view class="add1">收货人：{{shopAddress.name}}</view>
					<view class="add2">{{shopAddress.phone}}</view>
				</view>
			</view>
			<view class="addressList-list-bottom">
				收货地址：{{shopAddress.address}}
			</view>
		</view>
		<image src="/static/remao_shop/img/arrow_icon.png"></image>
	</view>
	<view class="addressListNone" :hidden="!isShowAddress">
		<image class="addressImg" src="/static/remao_shop/img/dingwei.png"></image>
		<view>请选择收货地址</view>
	</view>
</view>
<!-- 到店自提 -->
<view class="store" v-if="showMove">
	<image src="/static/remao_shop/img/address.png"></image>
	<view class="people">
		<text>提货人：</text>
		<input type="text" placeholder="提货人"></input>
	</view>
	<view class="people">
		<text>手机号码：</text>
		<input type="text" placeholder="手机号码"></input>
	</view>
	<view class="storeInfo">
		门店信息：山西省太原市小店区屋城街道飞云公寓
	</view>
</view>
<!-- 商品 -->
<view v-if="iskan == 1" class="popup-warp" :key="index">
	<view class="popup-pic fl">
		<image :src="img"></image>
	</view>
	<view class="pop-warp fr">
		<view class="pop-title">
			<text>{{name}}</text>
		</view>
		<view class="pop-current">
			<text>￥</text>
			<text>{{jiage}}</text>
		</view>
		<view class="pop-repertory fr">
			<text>x1</text>
		</view>
	</view>
</view>
<view v-for="(item, index) in shopList" :key="index" v-if="iskan != 1" class="popup-warp">
	<view class="popup-pic fl">
		<image :src="item.pic"></image>
	</view>
	<view class="pop-warp fr">
		<view class="pop-title">
			<text>{{item.name}}</text>
		</view>
		<view class="pop-spec">
			<text>{{item.pdt_desc}}</text>
		</view>
		<view class="pop-current">
			<text>￥</text>
			<text>{{item.original_price_amount}}</text>
		</view>
		<view class="pop-repertory fr">
			<text>x{{item.num}}</text>
		</view>
	</view>
</view>
<!-- </navigator> -->
<view class="total-warp">
	<view class="total fr">
		<view class="total-num">合计：</view>
		<view class="total-price">￥
			<text>{{shopsMoney}}</text>
			<text v-if="iskan == 1">{{jiage}}</text>
		</view>
	</view>
</view>

<!-- <view class='address' bindtap='number' wx:if="{{iskan != 1 && ismiaosha != 1}}">
  <text style='display:inline-block;margin-left:6rpx;color:red'>在线选号</text>
  <text>{{numbers}}</text>
</view> -->
<view class="address" v-if="iskan != 1">
	<text style="display:inline-block;margin-left:6rpx;">买家留言</text>
	<input class="fr" type="text" placeholder="选填"></input>
</view>
<view v-if="ismiaosha==0 && iskan!= 1" class="address" @tap="changeCoupon">
	<text style="display:inline-block;margin-left:6rpx;">我的优惠劵</text>
	<text style="color:red">{{couponTitle}}</text>
	<!-- <picker bindchange="bindCauseChange" value="{{index}}" range="{{cause}}" style='width:100%'>
    我的优惠劵
    <view class='fr r-choice'>
      <view class='r-title'>{{choice}}</view>
      <image src='../../img/arrow_icon.png'></image>
    </view>
  </picker> -->
</view>
<view class="tot-bot">
	<view class="total fr">
		<view class="total-num">实付：</view>
		<view class="total-price">￥
			<text>{{couponMoney}}</text>
			<text v-if="iskan == 1">{{jiage}}</text>
		</view>
	</view>
	<!-- <view bindtap='commitOrder' wx:if="{{iskan != 1}}" class='tot-btn fr'>
    <text>去支付</text>
  </view>
  <view bindtap='kanOrder' wx:if="{{iskan == 1}}" class='tot-btn fr'>
    <text>去支付</text>
  </view> -->
</view>
<!-- <view class='address' wx:if="{{iskan != 1}}" bindtap="weixinpayMethod">
  <text style='display:inline-block;margin-left:6rpx;'>支付方式</text>
  <text>{{ocean}}</text>
</view> -->

<!-- 自定义表单 -->
<view class="form" v-if="iskan != 1 && ismiaosha != 1">
	<!-- <view class='title'>实名认证</view> -->
	<view v-for="(item, index) in formList" :key="index" class="content">
		<view v-if="item.type == 'text'">
			<text v-if="item.require == 1">*</text>
			<view class="name">{{item.name}}:</view>
			<input :data-index="index" @input="nameinputFun" :value="item.default" :placeholder="item.placeholder"></input>
		</view>
		<view v-if="item.type == 'radio'">
			<text v-if="item.require == 1">*</text>
			<view class="name">{{item.name}}:</view>
			<radio-group class="radio-group" @change="radioChange" :data-index="index">
				<label v-for="(item, ind) in item.radio_name" :key="ind" class="radio">
					<radio :value="ind" checked></radio>{{item}}
				</label>
			</radio-group>
			<!-- <radio-group class="radio-group" bindchange="radioChange">
            <label class="radio" wx:for="{{danxuan}}" wx:for-index="index">
            {{item}}
            {{index}}
               <view wx:for="{{item}}" wx:for-index="ind">
                  <radio value="{{ind}}" checked="" />{{item}}
               </view>
            </label>
         </radio-group> -->
		</view>
		<view v-if="item.type == 'checkbox'">
			<text v-if="item.require == 1">*</text>
			<view class="name">{{item.name}}:</view>
			<checkbox-group :value="result" @change="onChangefu" :data-index="index">
				<checkbox v-for="(item, index2) in item.radio_name" :key="index2" :name="item">
					{{ item }}
				</checkbox>
			</checkbox-group>
		</view>
		<view v-if="item.type == 'textarea'">
			<text v-if="item.require == 1">*</text>
			<view class="name">{{item.name}}:</view>
			<textarea @input="textinput" :data-index="index" class="textarea" :placeholder="item.placeholder" @blur="bindTextAreaBlur" :value="item.default" auto-focus="true" auto-height></textarea>
			</view>
    <view v-if="item.type == 'time'">
      <text v-if="item.require == 1">*</text>
      <view class="name">{{item.name}}:</view>
      <view class="section">
        <picker mode="time" :value="time" :data-index="index" @change="bindTimeChange">
          <view class="picker">
            {{time}}
          </view>
        </picker>
      </view>
    </view>
    <view v-if="item.type == 'date'">
      <text v-if="item.require == 1">*</text>
      <view class="name">{{item.name}}:</view>
      <view class="section">
        <picker mode="date" :value="date" :data-index="index" @change="bindDateChange">
          <view class="picker">
            {{date}}
          </view>
        </picker>
      </view>
    </view>
    <view v-if="item.type == 'file'">
      <text v-if="item.require == 1">*</text>
      <view class="name">{{item.name}}:</view>
      <view class="imgupload" @tap="imguploadFun" :data-index="index">
        <image v-if="item.default == ''" src="/static/remao_shop/img/update.png" class="img"></image>
        <image v-if="item.default != ''" mode="aspectFit" :src="item.default"></image>
      </view>
    </view>
  </view>
  <!-- <button class="tijiao" bindtap="tijiao">提交表单</button> -->
</view>
<!-- <view class='bai'></view>
<view class='yuedu' wx:if="{{iskan != 1 && ismiaosha != 1}}">
  <view>
    <van-checkbox value="{{ checkeds }}" bind:change="onChangea"></van-checkbox>
    <view class='cont'>我已阅读并同意
      <text bindtap='ruwangfw' data-index="1">《中国联通移动业务用户入网服务协议》</text> </view>
  </view>
  <view>
    <van-checkbox value="{{ checked }}" bind:change="onChangee"></van-checkbox>
    <view class='cont'>我认可并遵守
      <text bindtap='ruwangfw' data-index="2">《通信业实名制信息要求》</text> </view>
  </view>
</view> -->
<!-- <view class='tot-bot'>
  <view class='total fl'>
    <view class='total-num'>实付：</view>
    <view class='total-price'>￥
      <text>{{couponMoney}}</text>
      <text wx:if="{{iskan == 1}}">{{jiage}}</text>
    </view>
  </view>
  <view bindtap='commitOrder' wx:if="{{iskan != 1}}" class='tot-btn fr'>
    <text>去支付</text>
  </view>
  <view bindtap='kanOrder' wx:if="{{iskan == 1}}" class='tot-btn fr'>
    <text>去支付</text>
  </view>
</view> -->
<view class="blockLayer wx" @tap="wechatPay" v-if="lshowone == '1'">
	<!-- <image src="../../img/wechatpay.png" class="payImg"></image> -->
	<!-- <text>线上支付</text> -->
	微信支付
</view>
<view class="blockLayer money" @tap="moneyPay" v-if="lshowtwo == '2'">
	<!-- <image src="../../img/moneypay.png" class="payImg"></image> -->
	<!-- <text>货到付款</text> -->
	货到付款
</view>
<!-- <view class="Onelayer" wx:if="{{close}}">
  <view class="Towlayer">
    <view class="layerHead">
      <text>支付方式</text>
      <image src="../../img/close.png" class="close" bindtap="closeLayer"></image>
    </view>
    <view>
      <view class="blockLayer" bindtap="wechatPay" wx:if="{{lshowone == '1'}}">
        <image src="../../img/wechatpay.png" class="payImg"></image>
        <text>线上支付</text>
      </view>
      <view class="blockLayer" bindtap="moneyPay" wx:if="{{lshowtwo == '2'}}">
        <image src="../../img/moneypay.png" class="payImg"></image>
        <text>货到付款</text>
      </view>
    </view>
  </view>
</view> -->
</view>
</template>

<script>
import api from "../../../api";
var app = getApp();

export default {
  data() {
    return {
      userId: '',
      // 切换标签
      tabs: ['快递配送', '到店自提'],
      tab: 0,
      // 到店自提
      showMove: false,
      type: '',
      // 商品列表
      shopList: [],
      // 商品总价
      shopsMoney: '',
      // 优惠提示
      couponTitle: '',
      // 优惠价格
      couponInitMoney: 0,
      // 优惠后价格
      couponMoney: '',
      //优惠券ID
      couponId: '',
      // 收货地址
      shopAddress: '',
      //是否有收货地址
      isShowAddress: '',
      // 购物车id
      cartId: '',
      // 是否积分兑换
      integral: '0',
      // 优惠券列表
      couponList: [],
      //--------------------
      //支付模块
      openId: '',
      // 支付方式
      // paytype: '0',
      // 订单编号
      order_sn: '',
      // 支付类型
      payType: 2,
      // 支付金额
      payMoney: '',
      // 判断该商品是否为秒杀商品
      ismiaosha: '',
      // 是否拼团普通0、拼团3
      orderType: '',
      // 拼团分享
      shareOrderId: 0,
      // 拼团分享订单id
      shareAssemble: '',
      //砍价
      img: '',
      name: '',
      kanid: '',
      iskan: '',
      jiage: '',
      order_id: '',
      //自定义表单
      formList: [],
      //input
      nameinput: '',
      //单选框
      danxuan: [],
      //复选框
      result: [],
      //多行文本框
      textarea: '',
      //时间选择
      time: '12:00',
      //日期选择
      date: '2019-1-1',
      //图片
      imgupload: '',
      form: [],
      //在线选号
      numbers: '',
      phoneList: [],
      checkeds: false,
      checked: false,
      // 支付方式
      ocean: "请选择",
      close: false,
      payMode: 1,
      isshowLayer: 1,
      lshowone: "0",
      lshowtwo: '0'
    };
  },

  components: {},
  props: {},
  onLoad: function (options) {
    this.payModeFun();
    wx.removeStorageSync('number');
    let openid = wx.getStorageSync("openid");
    let userid = wx.getStorageSync("userId");
    this.setData({
      openId: openid
    });

    if (options.oid) {
      this.setData({
        shareOrderId: options.oid
      });
    }

    if (!options.shareAssemble) {
      this.setData({
        shareAssemble: 0
      });
    } else {
      this.setData({
        shareAssemble: options.shareAssemble
      });
    }

    console.log(this.openId);

    var _self = this;

    console.log(options);

    if (options.type == 1) {
      var a = 0;
    } else if (options.type == 2) {
      var a = 1;
    }

    this.setData({
      userId: userid,
      // 是否立即结算
      type: a,
      cartId: options.cart_id,
      // 是否秒杀
      ismiaosha: options.ismiaosha,
      // 订单类型
      orderType: options.order_type,
      // 拼团分享订单id
      shareAssemble: options.shareAssemble
    });
    this.formFun();

    if (options.iskan == 1) {
      this.iskanlist();
      this.setData({
        iskan: options.iskan,
        img: options.img,
        name: options.name,
        kanid: options.cart_id,
        jiage: options.jiage,
        payMoney: options.jiage,
        payType: options.type
      });
    }

    console.log(this.kanid, this.jiage);
    this.getlist();
    console.log(this.shareOrderId, "orderID");
  },
  //监听页面显示
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'number',

      success(res) {
        console.log(res.data);
        that.setData({
          numbers: res.data
        });
      }

    });
    console.log(this.numbers);
    that.iskanlist();
    that.getlist();
  },
  //生命周期函数--监听页面卸载
  onUnload: function () {
    let a = wx.getStorageSync('couponId');
    console.log(a);

    if (a != '') {
      wx.removeStorageSync('couponId');
    } else {
      return;
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.iskanlist();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  methods: {
    payModeFun: function () {
      app.globalData.request({
        url: api.gzSea.paymode,
        data: {},
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        success: res => {
          console.info(res);
          var a = res.data[0];
          var b = res.data[1];

          if (a == '1') {
            this.setData({
              lshowone: a
            });
          }

          if (b == '2') {
            this.setData({
              lshowtwo: b
            });
          }
        }
      });
    },

    onChangea(event) {
      this.setData({
        checkeds: event.detail
      });
    },

    onChangee(event) {
      this.setData({
        checked: event.detail
      });
    },

    // 选择优惠券
    changeCoupon: function () {
      wx.navigateTo({
        url: '../changeCoupon/changeCoupon?userId=' + this.userId + '&money=' + this.shopsMoney
      });
    },
    // tab切换
    select: function (e) {
      this.setData({
        tab: e.currentTarget.dataset.index
      });

      if (e.currentTarget.dataset.index == 1) {
        this.setData({
          showMove: true
        });
      } else {
        this.setData({
          showMove: false
        });
      }

      console.log(this.showMove);
    },
    payMethod: function () {},
    // 砍价获取默认收货地址
    iskanlist: function () {
      app.globalData.request({
        url: api.default.user_address,
        data: {
          uid: this.userId
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        success: res => {
          console.log(res);
          this.setData({
            shopAddress: res.default_address
          }); // 判断是否有地址

          if (res.default_address == '') {
            this.setData({
              isShowAddress: true
            });
          } else {
            this.setData({
              isShowAddress: false
            });
          }
        }
      });
    },
    // 加载数据
    getlist: function () {
      var that = this;
      app.globalData.request({
        url: api.fyz.post_cart,
        data: {
          uid: that.userId,
          type: that.type,
          cart_id: that.cartId
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        success: res => {
          console.log(res);
          let money = null; // 判断是否有地址

          if (res.default_address == '') {
            that.setData({
              isShowAddress: true
            });
          } else {
            that.setData({
              isShowAddress: false
            });
          } // 商品总价


          that.shopsMoney = '';

          for (let a = 0; a < res.goods_list.length; a++) {
            let moneyMoney = parseFloat(res.goods_list[a].final_price);
            money += moneyMoney;
          }

          money = money.toFixed(2);
          console.log(money);
          this.setData({
            shopAddress: res.default_address,
            //地址
            shopList: res.goods_list,
            //商品列表
            shopsMoney: money,
            //商品总价
            couponMoney: money - that.couponInitMoney //优惠后价格

          }); //列表渲染完成再加载优惠券列表

          that.getcoupon();
          console.log(this.shopList[0]);
          this.phone();
        },
        fail: function (res) {},
        complete: function (res) {}
      });
    },
    // 选择地址路由
    toChangeAddress: function () {
      wx.navigateTo({
        url: '../changeAddress/changeAddress?userId=' + this.userId
      });
    },
    // 获取优惠卷列表
    getcoupon: function () {
      let that = this;
      app.globalData.request({
        url: api.default.coupon_index,
        data: {
          uid: that.userId
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        success: res => {
          console.log(res.coupon); // 判断有无优惠券

          if (res.coupon.length == 0) {
            console.log("111");
            that.setData({
              couponList: '',
              couponTitle: '暂无可用优惠券'
            });
          } else {
            var listA = [];
            var listB = []; // 筛选是否未使用

            for (let a = 0; a < res.coupon.length; a++) {
              if (res.coupon[a].status == 4) {
                listA.push(res.coupon[a]);
              }
            }

            console.log(listA); //筛选最低使用金额

            for (let a = 0; a < listA.length; a++) {
              let minNum = parseFloat(listA[a].min_amount);
              let shopsNum = parseFloat(that.shopsMoney);
              console.log(minNum, shopsNum);

              if (minNum < shopsNum || minNum == shopsNum) {
                // console.log(listA[a])
                listB.push(listA[a]);
                console.log(listB); // listB = listA
              }
            } // 是否有满足条件可用的优惠


            if (listB.length == 0) {
              console.log("222");
              that.setData({
                couponList: '',
                couponTitle: '暂无可用优惠券'
              });
            } else {
              that.setData({
                couponList: listB,
                couponTitle: listB.length + '张可用'
              });
            }

            that.isCoupon();
          }
        },
        fail: function (res) {},
        complete: function (res) {}
      });
    },

    // 更新优惠券状态
    isCoupon() {
      let that = this;
      let couponHave = wx.getStorageSync("couponId"); //判断是否选取优惠券

      if (couponHave != '') {
        // console.log('111')
        // 判断是否选择不使用优惠券
        if (couponHave == 0) {
          that.setData({
            couponTitle: '不使用优惠券',
            couponInitMoney: 0
          });
          let cpMoney = that.couponInitMoney;
          console.log(cpMoney);
          that.setData({
            couponMoney: that.shopsMoney - cpMoney,
            couponId: ''
          });
        } else {
          console.log(that.couponMoney);
          console.log(that.couponInitMoney);

          for (let a = 0; a < that.couponList.length; a++) {
            if (that.couponList[a].my_id == couponHave) {
              that.setData({
                couponTitle: '-' + that.couponList[a].discount,
                couponInitMoney: that.couponList[a].discount
              });
            }
          }

          that.setData({
            couponMoney: that.shopsMoney - that.couponInitMoney,
            couponId: couponHave
          });
          console.log(that.couponInitMoney);
          console.log(that.couponMoney);
        }
      } else {
        // console.log('22222')
        return;
      }
    },

    wechatPay: function () {
      wx.showLoading({
        title: '请稍候'
      });
      console.warn("微信支付");
      this.setData({
        payMode: 1,
        isshowLayer: 2,
        close: false,
        ocean: "线上支付"
      });
      this.commitOrder();
    },
    moneyPay: function () {
      wx.showLoading({
        title: '请稍候'
      });
      console.warn("货到付款");
      this.setData({
        payMode: 2,
        isshowLayer: 2,
        close: false,
        ocean: "货到付款"
      });
      this.commitOrder();
    },
    closeLayer: function () {
      this.setData({
        isshowLayer: 1,
        close: false
      });
    },

    weixinpayMethod() {
      this.setData({
        close: true
      });
    },

    // 提交订单
    commitOrder: function () {
      if (this.isshowLayer == 1) {
        this.setData({
          close: true
        });
      } else if (this.isshowLayer == 2) {
        if (this.payMode == 1) {
          //paymode为1 微信支付
          if (this.iskan != 1 && this.ismiaosha == 0) {
            var aa = 0;

            if (this.formList) {
              for (let i = 0; i < this.formList.length; i++) {
                // for (let i = 0; i < 0; i++) {
                if (this.formList[i].default == "" && this.formList[i].require == 1) {
                  aa = i;
                }
              }
            }

            console.log(this.formList);
            console.log(aa);

            if (aa != 0) {
              wx.showToast({
                title: '请输入必填项',
                icon: 'none',
                duration: 2000
              });
            } //  else
            // if (this.data.checkeds == false || this.data.checked == false) {
            //   wx.showToast({
            //     title: '请勾选协议',
            //     icon: 'none',
            //     duration: 2000
            //   })
            // } 
            else {
                let that = this;
                let form = JSON.stringify(that.formList);
                console.log(that.userId);
                console.log(that.shopAddress.id);
                console.log(that.integral);
                console.log(that.shareOrderId, "团长ID"); //  that.payMode();

                app.globalData.request({
                  url: api.fyz.createOrder,
                  data: {
                    payment_id: that.payMode,
                    uid: that.userId,
                    address_id: that.shopAddress.id,
                    integral: that.integral,
                    coupon_id: that.couponId,
                    order_type: that.orderType,
                    share_order_id: that.shareOrderId,
                    form: form,
                    number: that.numbers
                  },
                  header: {
                    'content-type': 'application/x-www-form-urlencoded' // 默认值

                  },
                  method: 'POST',
                  success: res => {
                    console.log(res);

                    if (res.status == 1) {
                      that.setData({
                        order_sn: res.order_sn,
                        payMoney: res.order_amount
                      }); // wx.navigateTo({
                      //   url: '../pay/pay?type=' + type + '&order=' + res.data.order_sn + '&money=' + res.data.order_amount + '&userId=' + that.data.userId,
                      // })

                      that.weixinPayMoney();
                    } else if (res.status == 0) {
                      wx.showToast({
                        title: '提交失败',
                        duration: 1000
                      });
                    } else if (res.status == 3) {
                      wx.showToast({
                        title: '请填写地址',
                        duration: 1000
                      });
                    }
                  },
                  fail: function (res) {},
                  complete: function (res) {
                    wx.setStorage({
                      key: 'orderID',
                      data: 0
                    });
                  }
                });
              }
          } else {
            let that = this;
            let form = JSON.stringify(that.formList);
            console.log(that.userId);
            console.log(that.shopAddress.id);
            console.log(that.integral);
            console.log(that.shareOrderId, "团长ID"); //  that.payMode();

            app.globalData.request({
              url: api.fyz.createOrder,
              data: {
                payment_id: that.payMode,
                uid: that.userId,
                address_id: that.shopAddress.id,
                integral: that.integral,
                coupon_id: that.couponId,
                order_type: that.orderType,
                share_order_id: that.shareOrderId,
                form: form,
                number: that.numbers
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值

              },
              method: 'POST',
              success: res => {
                console.log(res);

                if (res.status == 1) {
                  that.setData({
                    order_sn: res.order_sn,
                    payMoney: res.order_amount
                  }); // wx.navigateTo({
                  //   url: '../pay/pay?type=' + type + '&order=' + res.data.order_sn + '&money=' + res.data.order_amount + '&userId=' + that.data.userId,
                  // })

                  that.weixinPayMoney();
                } else if (res.status == 0) {
                  wx.showToast({
                    title: '提交失败',
                    duration: 1000
                  });
                } else if (res.status == 3) {
                  wx.showToast({
                    title: '请填写地址',
                    duration: 1000
                  });
                }
              },
              fail: function (res) {},
              complete: function (res) {
                wx.setStorage({
                  key: 'orderID',
                  data: 0
                });
              }
            });
          }
        } else if (this.payMode == 2) {
          console.log("货到付款");

          if (this.iskan != 1 && this.ismiaosha == 0) {
            var aa = 0; // for (let i = 0; i < this.data.formList.length; i++) {

            for (let i = 0; i < 0; i++) {
              if (this.formList[i].default == "" && this.formList[i].require == 1) {
                aa = i;
              }
            }

            console.log(this.formList);
            console.log(aa);

            if (aa != 0) {
              wx.showToast({
                title: '请输入必填项',
                icon: 'none',
                duration: 2000
              });
            } //  else
            // if (this.data.checkeds == false || this.data.checked == false) {
            //   wx.showToast({
            //     title: '请勾选协议',
            //     icon: 'none',
            //     duration: 2000
            //   })
            // }
            else {
                let that = this;
                let form = JSON.stringify(that.formList);
                console.log(that.userId);
                console.log(that.shopAddress.id);
                console.log(that.integral);
                console.log(that.shareOrderId, "团长ID"); //  that.payMode();

                app.globalData.request({
                  url: api.fyz.createOrder,
                  data: {
                    payment_id: that.payMode,
                    uid: that.userId,
                    address_id: that.shopAddress.id,
                    integral: that.integral,
                    coupon_id: that.couponId,
                    order_type: that.orderType,
                    share_order_id: that.shareOrderId,
                    form: form,
                    number: that.numbers
                  },
                  header: {
                    'content-type': 'application/x-www-form-urlencoded' // 默认值

                  },
                  method: 'POST',
                  success: res => {
                    console.log(res);

                    if (res.status == 1) {
                      that.setData({
                        order_sn: res.order_sn,
                        payMoney: res.order_amount
                      });
                      wx.redirectTo({
                        url: '../../packageB/order/order?status=0&userId=' + that.userId
                      });
                    } else if (res.status == 0) {
                      wx.showToast({
                        title: '提交失败',
                        duration: 1000
                      });
                    } else if (res.status == 3) {
                      wx.showToast({
                        title: '请填写地址',
                        duration: 1000
                      });
                    }
                  },
                  fail: function (res) {},
                  complete: function (res) {
                    wx.setStorage({
                      key: 'orderID',
                      data: 0
                    });
                  }
                });
              }
          } else {
            let that = this;
            let form = JSON.stringify(that.formList);
            console.log(that.userId);
            console.log(that.shopAddress.id);
            console.log(that.integral);
            console.log(that.shareOrderId, "团长ID"); //  that.payMode();

            app.globalData.request({
              url: api.fyz.createOrder,
              data: {
                payment_id: that.payMode,
                uid: that.userId,
                address_id: that.shopAddress.id,
                integral: that.integral,
                coupon_id: that.couponId,
                order_type: that.orderType,
                share_order_id: that.shareOrderId,
                form: form,
                number: that.numbers
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值

              },
              method: 'POST',
              success: res => {
                wx.redirectTo({
                  url: '../../packageB/order/order?status=0&userId=' + _that.userId
                });
              },
              fail: function (res) {},
              complete: function (res) {}
            });
          }
        }
      }
    },
    // 砍价提交订单
    kanOrder: function () {
      let that = this;
      console.log(that.kanid);
      console.log(that.jiage);
      console.log(that.shopAddress.id);
      app.globalData.request({
        url: api.default.bargaincreate_order,
        data: {
          id: that.kanid,
          price: that.jiage,
          user_id: that.userId,
          address_id: that.shopAddress.id
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        success: res => {
          console.log(res);

          if (res.status == 1) {
            that.setData({
              order_sn: res.order_sn,
              order_id: res.order_id
            });
            that.weixinPayMoney();
          } else if (res.status == 0) {
            wx.showToast({
              title: '提交失败',
              duration: 1000
            });
          } else if (res.status == 3) {
            wx.showToast({
              title: '请填写地址',
              duration: 1000
            });
          }
        },
        fail: function (res) {}
      });
    },

    // 微信支付
    weixinPayMoney() {
      var _that = this; // console.log(_that.data.order)
      // console.log(_that.data.type)
      // console.log(_that.data.payMoney)


      app.globalData.request({
        url: api.fyz.weixinPay,
        data: {
          type: _that.payType,
          pay_sn: _that.order_sn,
          money: _that.payMoney,
          openid: _that.openId
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        success: res => {
          wx.hideLoading();
          console.log(res);
          var prepayid = res.ioswx_config.prepayid,
              osn = res.osn;
          console.log('支付id:', prepayid); //  付款成功

          if (res.status == 1) {
            wx.requestPayment({
              appId: res.weixin_config.appid,
              nonceStr: res.weixin_config.nonce_str,
              package: 'prepay_id=' + res.weixin_config.prepay_id,
              signType: 'MD5',
              timeStamp: res.weixin_config.timestamp,
              paySign: res.weixin_config.sign,
              success: function (res1) {
                wx.getStorage({
                  key: 'userId',
                  success: function (aaa) {
                    console.log(aaa.data);
                    var open = aaa.data;
                    console.log(open);
                    app.globalData.request({
                      url: api.gzSea.message,
                      //仅为示例，并非真实的接口地址
                      data: {
                        sole: prepayid,
                        order_sn: osn,
                        user_id: open
                      },
                      method: 'POST',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded' // 默认值

                      },

                      success(res) {
                        console.log(res);
                      }

                    });
                  }
                });

                if (_that.iskan != 1) {
                  //  更新订单状态
                  app.globalData.request({
                    url: api.fyz.updataOrder,
                    data: {
                      user_id: _that.userId,
                      order_sn: _that.order_sn,
                      payment_id: 2
                    },
                    header: {
                      'content-type': 'application/x-www-form-urlencoded' // 默认值

                    },
                    method: 'POST',
                    success: res2 => {
                      console.log(res2);

                      if (res2.status == 1) {
                        console.log(_that.userId);
                        wx.redirectTo({
                          url: '../../packageB/order/order?status=0&userId=' + _that.userId
                        });
                        wx.removeStorageSync('couponId');
                      } else {
                        wx.showToast({
                          title: res.msg,
                          duration: 1000
                        });
                      }
                    }
                  });
                }

                if (_that.iskan == 1) {
                  //  更新砍价订单状态
                  app.globalData.request({
                    url: api.default.bargainorder_update_pay,
                    data: {
                      order_id: _that.order_id
                    },
                    header: {
                      'content-type': 'application/x-www-form-urlencoded' // 默认值

                    },
                    method: 'POST',
                    success: res => {
                      console.log(res);

                      if (res.status == 1) {
                        // wx.showToast({
                        //    title: res.msg,
                        // })
                        setTimeout(function () {
                          wx.navigateBack({
                            delta: 2
                          });
                        }, 500); // wx.redirectTo({
                        //   url: '../../packageB/order/order?status=0&userId=' + _that.data.userId,
                        // })
                        // wx.removeStorageSync('couponId')
                      } else {
                        wx.showToast({
                          title: res.msg,
                          duration: 1000
                        });
                      }
                    }
                  });
                }
              },
              fail: function (res2) {
                wx.showToast({
                  title: '支付失败',
                  icon: 'none',
                  duration: 1000
                });
              }
            });
          }
        },
        fail: function (ret) {
          console.log(ret);
        },
        complete: function (reb) {
          console.log(reb);
        }
      });
    },

    //自定义表单
    formFun: function () {
      app.globalData.request({
        url: api.default.order_select_form,
        data: {},
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        success: res => {
          console.log(res);
          this.setData({
            formList: res.data
          });
          var that = this; // for (let i = 0; i < that.data.formList.length; i++) {

          for (let i = 0; i < 0; i++) {
            if (that.formList[i].type == 'time') {
              that.formList[i].default = that.time;
            }

            if (that.formList[i].type == 'date') {
              that.formList[i].default = that.date;
            }
          }

          console.log(this.formList);
        }
      });
    },

    //input
    nameinputFun(e) {
      console.log(e);
      console.log(e.detail.value);
      var idx = e.currentTarget.dataset.index;
      var list = this.formList; // 

      var list2 = list[idx];
      list2.default = e.detail.value;
      console.log(list);
      this.setData({
        formList: list
      });
    },

    //textarea多行文本框
    textinput(e) {
      console.log(e);
      console.log(e.detail.value);
      var idx = e.currentTarget.dataset.index;
      var list = this.formList; // 

      var list2 = list[idx];
      list2.default = e.detail.value;
      console.log(list);
      this.setData({
        textarea: list
      });
    },

    //单选框
    radioChange(event) {
      console.log(event.currentTarget.dataset.index);
      console.log(event.detail.value);
      var idx = event.currentTarget.dataset.index;
      var val = event.detail.value;
      var list = this.formList;
      var list2 = list[idx];
      list2.default = list2.radio_name[event.detail.value];
      console.log(list2.radio_name[event.detail.value]);
      console.log(this.formList);
    },

    //复选框
    onChangefu(event) {
      var idx = event.currentTarget.dataset.index;
      this.setData({
        result: event.detail
      });
      var list = this.formList;
      var list2 = list[idx];
      list2.default = event.detail;
      console.log(this.result);
      console.log(this.formList);
    },

    //时间选择
    bindTimeChange: function (e) {
      console.log('picker发送选择改变，携带值为', e.detail.value);
      console.log(e);
      this.setData({
        time: e.detail.value
      });
      console.log(e.detail.value);
      var idx = e.currentTarget.dataset.index;
      var list = this.formList;
      var list2 = list[idx];
      list2.default = e.detail.value;
      console.log(list);
    },
    //日期选择
    bindDateChange: function (e) {
      console.log('picker发送选择改变，携带值为', e.detail.value);
      console.log(e);
      this.setData({
        date: e.detail.value
      });
      console.log(e.detail.value);
      var idx = e.currentTarget.dataset.index;
      var list = this.formList;
      var list2 = list[idx];
      list2.default = e.detail.value;
      console.log(list);
    },

    //图片
    imguploadFun(e) {
      console.log(e);
      var idx = e.currentTarget.dataset.index;
      var that = this;
      var list = that.formList;
      var list2 = list[idx];
      console.log(list);
      console.log(list2);
      wx.chooseImage({
        count: 1,

        success(res) {
          // console.log(res)
          // console.log(res)
          const tempFilePaths = res.tempFilePaths;
          that.Logo = tempFilePaths[0];
          console.log(tempFilePaths[0]);
          wx.uploadFile({
            url: api.default.wq_uplode_img,
            filePath: tempFilePaths[0],
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: function (res) {
              console.log(res);
              console.log(res.data); // var src = that.data.formList[idx].src = 

              list2.default = res.data;
              that.setData({
                formList: list
              });
            }
          });
        }

      });
    },

    //提交表单
    tijiao: function () {
      console.log(this.formList);
      app.globalData.request({
        url: api.default.orderform_post,
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        data: {},
        method: 'POST',
        success: res => {
          console.log(res);
        }
      });
    },
    //手机号
    number: function () {
      console.log(this.shopList[0].goods_id);
      wx.navigateTo({
        url: '../../packageC/number/number?goods_id=' + this.shopList[0].goods_id
      });
    },
    phone: function () {
      var that = this;
      console.log(that.shopList[0].goods_id);
      app.globalData.request({
        url: api.default.goodsacquire_number,
        data: {
          goods_id: that.shopList[0].goods_id,
          page: 1,
          keyword: ''
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        success: res => {
          console.log(res);
          this.setData({
            numbers: res.data[0].number
          });
        }
      });
    },
    //业务
    ruwangfw: function (e) {
      console.log(e.currentTarget.dataset.index);
      wx.navigateTo({
        url: '../../packageC/professional/professional?index=' + e.currentTarget.dataset.index
      });
    }
  }
};
</script>
<style>
@import "./affirm.css";
</style>